package cn.lh.pet.service.impl;

import cn.lh.basic.jwt.JwtUtils;
import cn.lh.basic.jwt.Payload;
import cn.lh.basic.jwt.RsaUtils;
import cn.lh.basic.service.IBaiduAiAuditService;
import cn.lh.basic.util.*;
import cn.lh.order.domain.OrderPetAcquisition;
import cn.lh.order.mapper.OrderPetAcquisitionMapper;
import cn.lh.org.domain.Employee;
import cn.lh.org.domain.Shop;
import cn.lh.org.exception.BusinessException;
import cn.lh.org.mapper.EmployeeMapper;
import cn.lh.org.mapper.ShopMapper;
import cn.lh.pet.domain.Pet;
import cn.lh.pet.domain.SearchMasterMsg;
import cn.lh.pet.domain.SearchMasterMsgAuditLog;
import cn.lh.pet.dto.AcceptDto;
import cn.lh.pet.mapper.PetMapper;
import cn.lh.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.lh.pet.mapper.SearchMasterMsgMapper;
import cn.lh.pet.query.SearchMasterMsgQuery;
import cn.lh.pet.service.ISearchMasterMsgService;
import cn.lh.basic.service.impl.BaseServiceImpl;
import cn.lh.user.domain.Logininfo;
import cn.lh.user.domain.User;
import cn.lh.user.mapper.UserMapper;
import cn.lh.user.util.LoginData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    PetMapper petMapper;
    @Autowired
    OrderPetAcquisitionMapper orderPetAcquisitionMapper;


    @Override
    public void publish(SearchMasterMsg searchMasterMsg, HttpServletRequest req) {
        try {
            Logininfo logininfo = LoginContext.getLogininfo(req);
            User user = userMapper.loadByLogininfoId(logininfo.getId());
            searchMasterMsg.setUserId(user.getId());
            searchMasterMsgMapper.save(searchMasterMsg);
            boolean result1 = baiduAiAuditService.textAudit(searchMasterMsg.getTitle() + searchMasterMsg.getName() + searchMasterMsg.getAddress());
            boolean result2 = baiduAiAuditService.imgAudit(searchMasterMsg.getResources());

            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            if (result1 && result2) {
                Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
                List<Shop> shops = shopMapper.loadAll();
                Shop shop = DistanceUtils.getNearestShop(point, shops);
                searchMasterMsg.setShopId(shop.getId());
                searchMasterMsg.setState(1);
                searchMasterMsg.setNote("内容合法，审核成功");
                searchMasterMsgMapper.update(searchMasterMsg);
                searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
                searchMasterMsgAuditLog.setState(1);
                searchMasterMsgAuditLog.setNote("内容合法，审核成功");
                searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
            } else {
                searchMasterMsg.setState(0);
                searchMasterMsg.setNote("审核失败，内容非法");
                searchMasterMsgMapper.update(searchMasterMsg);

                //2.2.审核失败：修改寻主消息状态0 + 添加审核日志
                searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
                //audit_id - 自动审核，没有添加审核人
                searchMasterMsgAuditLog.setState(0);//驳回
                searchMasterMsgAuditLog.setNote("审核失败，内容非法");
                searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
                throw new BusinessException("审核失败，内容非法");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Page<SearchMasterMsg> userSearchMasterMsg(SearchMasterMsgQuery query, HttpServletRequest req) {
        Logininfo logininfo = LoginContext.getLogininfo(req);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public Page<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest req) {
        Logininfo logininfo = LoginContext.getLogininfo(req);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        query.setShopId(employee.getShop_id());
        query.setState(1);
        return super.queryPage(query);
    }

    @Override
    public void reject(long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(AcceptDto acceptDto) {
        Long handler = acceptDto.getHandler();
        Long msgId = acceptDto.getMsgId();
        String note = acceptDto.getNote();
        OrderPetAcquisition orderPetAcquisitionTmp = orderPetAcquisitionMapper.loadBySmmId(msgId);
        if (orderPetAcquisitionTmp != null) {
            throw new BusinessException("重复接单");
        }
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        petMapper.save(pet);
        OrderPetAcquisition orderPetAcquisition = buildPetAcquisitionOrder(searchMasterMsg, handler, pet);
        orderPetAcquisitionMapper.save(orderPetAcquisition);
    }

    private Pet searchMasterMsg2Pet(SearchMasterMsg smm) {
        Pet pet = new Pet();
        pet.setName(smm.getName());
        pet.setCostprice(smm.getPrice());
        pet.setTypeId(smm.getPetType());
        pet.setResources(smm.getResources());
        pet.setShopId(smm.getShopId());
        pet.setSearchMasterMsgId(smm.getId());
        return pet;
    }

    private OrderPetAcquisition buildPetAcquisitionOrder(SearchMasterMsg searchMasterMsg, Long handler, Pet pet) {

        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(handler);
        order.setOrderSn(orderSn);
        order.setDigest(searchMasterMsg.getName() + "的收购订单");
        //最后收购是当前时间+2两天
        long lastcomfirmtimeLong = System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 2;
        order.setLastcomfirmtime(new Date(lastcomfirmtimeLong));
        order.setState(0);
        order.setPrice(searchMasterMsg.getPrice());
        //        order.setPaytype(); //现金支付
        order.setPetId(pet.getId());
        order.setUserId(searchMasterMsg.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(searchMasterMsg.getAddress());
        order.setEmpId(handler);
        order.setSearchMasterMsgId(searchMasterMsg.getId());
        return order;
    }

}
